package com.mastercard.labs

import grails.converters.JSON
import org.apache.shiro.SecurityUtils

import java.text.SimpleDateFormat

class DashboardController {

	def cardService, transactionService, categoryService, transactionCategoryService, dealService, userService, merchantService, voucherService

	def index() {
		dashboard()
	}

	def dashboard() {

		// Get cards
		//def user = User.findByEmail("zifeng@gmail.com")
		def user = SecurityUtils.subject.session.getAttribute("current_user")

		def usrRole
		def usr = User.findByUsername(user.username.toUpperCase())
		if(usr.roles && usr.roles.size() > 0){
			usrRole = ((Set)usr.roles).iterator().next();
		}

		if(usrRole && usrRole.name.toLowerCase() == "admin"){
			adminDashBoard()
		}else{
			def cards = cardService.getCards(user)
			def endStr = params.get("to_date")
			def startStr = params.get("from_date")
			Date fromDate
			def fmt = new SimpleDateFormat("dd-MM-yyyy")
			
			if (startStr != null) {
				fromDate = fmt.parse(startStr);
			} else {
				Calendar cal = Calendar.getInstance()
				cal.add(Calendar.MONTH, -2)
				fromDate = cal.getTime()
			}

			Date toDate
			if (endStr != null) {
				toDate = fmt.parse(endStr);
			} else {
				toDate = new Date()
			}
			
			def formatter = new SimpleDateFormat("dd-MMM-yyyy")
			// Get transactions
			def transactions = transactionService.getUserTransactions(user, fromDate, toDate)
			def monthlySpending = transactionService.getTotalSpending(user, fromDate, toDate)
			HashMap summaryMap = transactionService.getSummary(user)
			render (view: 'dashboard', model:[cardsJSON:new JSON(cards).toString(),
						transactions: transactions,
						dateFormat: formatter,
						fmt: fmt,
						monthlySpending: new JSON(monthlySpending),
						categories: categoryService.getAll(),
						transactionCategoryService: transactionCategoryService,
						deals: dealService.getDeals(user),
						summaryMap: summaryMap,
						topCardSpending: transactionService.getTopCardSpendingSummary(user, fromDate, toDate),
						topCategorySpending: transactionService.getTopCategorySpendingSummary(user, fromDate, toDate),
						fromDate: fromDate,
						toDate: toDate])
		}
	}

	def profile() {
		//def user = User.findByEmail("zifeng@gmail.com")
		def user = SecurityUtils.subject.session.getAttribute("current_user")
		render (view: 'report', model:[
					deals: dealService.getDeals(user)])
	}

	def adminDashBoard(){
		def userInstanceList = userService.searchUserForDashboard()
		def merchantInstanceList = merchantService.searchMerchantForDashboard()
		def dealInstanceList = dealService.searchDealForDashboard()
		def voucherInstanceList = voucherService.searchVoucherForDashboard()

		render (view: "dashboard_admin", model: [userInstanceList: userInstanceList, merchantInstanceList: merchantInstanceList, dealInstanceList: dealInstanceList, voucherInstanceList: voucherInstanceList])
	}
}